package expressToAltaRica;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.StringWriter;


import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.xml.bind.attachment.AttachmentMarshaller;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import com.sun.xml.xsom.XSFacet;
import com.sun.xml.xsom.XSRestrictionSimpleType;
import com.sun.xml.xsom.XSSchema;
import com.sun.xml.xsom.XSSimpleType;
import com.sun.xml.xsom.parser.SchemaDocument;
import com.sun.xml.xsom.parser.XSOMParser;
import com.sun.xml.xsom.visitor.XSVisitor;

public class AddTypes {

	XSOMParser parser ;
	File xsdFile;
	Document docGen;


	public AddTypes(String xsdPath) throws ParserConfigurationException{
		this.parser= new XSOMParser();
		this.xsdFile=new File(xsdPath);
		DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
		DocumentBuilder db=factory.newDocumentBuilder();
		this.docGen=db.newDocument();
	}


	public Element generateTypes() throws SAXException, IOException{
		//the element result
		Element eTypes=this.docGen.createElement("Types");
		this.parser.parse(this.xsdFile);
		//get the schemadocument
		Set<SchemaDocument> shDocs=this.parser.getDocuments();
		Iterator it= shDocs.iterator();
		//get the schema, we know that there's an only schema so no need to have a loop
		SchemaDocument shDoc=(SchemaDocument)it.next();
		// get the schema
		XSSchema sh= shDoc.getSchema();
		// get the simple types which correspond to the types defined at contexte_janvier.exp
		Map<String, XSSimpleType> types= (Map<String, XSSimpleType>)sh.getSimpleTypes();
		System.out.println("les types recuperes : " +types.values().toString());
		Set cles=types.keySet();
		Iterator itCles=cles.iterator();
		//the number of the type
		int i=0; 
		//each simple type is a new tag TYPE_FAMILY
		while(itCles.hasNext()){
			Element typeFam=this.docGen.createElement("TYPE_FAMILY");
			//the tag IDENTIFIACTION
			Element idFam= this.docGen.createElement("IDENTIFICATION");
			idFam.setAttribute("NAME", "Type_"+i);
//			Attr aName= this.docGen.createAttribute("NAME");
//			aName.setValue("TYPE_"+i);
//			Attr agpAcc= this.docGen.createAttribute("GROUP_ACCESS");
//			agpAcc.setValue("1");
//			idFam.appendChild(agpAcc);
//			idFam.insertBefore(aName, agpAcc);
			idFam.setAttribute("GROUP_ACCESS", "1");
			idFam.setAttribute("OTHER_ACCESS", "0");
			idFam.setAttribute("GROUP", "admins");
			idFam.setAttribute("OWNER", "admin");
			i++;
			typeFam.appendChild(idFam);
			//</IDENTIFIACTION>

			Element type=this.docGen.createElement("TYPE");
			Element idType= this.docGen.createElement("IDENTIFICATION");
			String cle= (String)itCles.next();
			//get the simpletype from the list
			XSSimpleType typeTag= (XSSimpleType)types.get(cle);
			//get the name of the simple type
			String nameType=typeTag.getName();
			System.out.println("type name = "+nameType);
			SimpleDateFormat df= new SimpleDateFormat("dd/MM/yy h:mm a");
			String d= df.format(new Date());
			idType.setAttribute("NAME", nameType);
			idType.setAttribute("VERSION", "1");
			idType.setAttribute("RELEASE", "3");
			idType.setAttribute("CREATION_DATE", d);
			idType.setAttribute("UPDATE_DATE", d);
			idType.setAttribute("GROUP_ACCESS", "1");
			idType.setAttribute("OTHER_ACCESS", "0");
			idType.setAttribute("GROUP", "admins");
			idType.setAttribute("OWNER", "admin");
			idType.setAttribute("COMMENT", "");
			idType.setAttribute("FREEZE", "false");
			type.appendChild(idType);
			XSRestrictionSimpleType res= typeTag.asRestriction();
			ArrayList<XSFacet> fcs= (ArrayList<XSFacet>)res.getDeclaredFacets();
			Iterator itFcs=fcs.iterator();
			//	XSFacet[] fcsArr=(XSFacet[]) fcs.toArray();
			if(fcs==null || fcs.size()==0)
				System.out.println("liste vide");
			for(int j=0;j<fcs.size();j++){
				XSFacet fac=(XSFacet)fcs.get(j);
				Element field= this.docGen.createElement("FIELD");
				field.setAttribute("NAME",fac.getValue().value);
				//				System.out.println("value facte recupere = "+fac.getValue().value);
				type.appendChild(field);
			}
			typeFam.appendChild(type);
			eTypes.appendChild(typeFam);
		}

		return eTypes;
	}

	public static void main(String[] args){
		try {
			AddTypes a=new AddTypes("/home/ubuntu/workspace_indigo/ProjetLongJSDAI/src/expressToAltaRica/cool.xsd");
			Element e=a.generateTypes();
			a.docGen.appendChild(e);
			DOMSource domSource = new DOMSource(a.docGen);
			StringWriter writer = new StringWriter();
			StreamResult result = new StreamResult(writer);
			TransformerFactory tf = TransformerFactory.newInstance();
			Transformer transformer = tf.newTransformer();
			transformer.transform(domSource, result);
			String text = writer.toString();
			System.out.println("text: " + text);

			FileWriter fw = new FileWriter ("types.xml");
			BufferedWriter bw = new BufferedWriter (fw);
			PrintWriter fichierSortie = new PrintWriter (bw); 
			fichierSortie.println (text); 
			fichierSortie.close();


		} catch (ParserConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	   

		catch(TransformerException ex)
		{
			ex.printStackTrace();
		}
		catch (Exception e)
		{
			System.out.println(e.toString());
		}

	}

}
